import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;


public class Connection {
	private StreamConnection m_Connection;
	private DataInputStream m_In;
	private DataOutputStream m_Out;
    private String m_Url; // urlStrings used for connecting, for server this is empty.
    private boolean m_AutoFlush = false;
    
    /*
     * local device = server
     */
    public Connection(StreamConnection connection) throws IOException {
    	m_Url = "";
    	m_Connection = connection;
    	m_In = m_Connection.openDataInputStream();
    	m_Out = m_Connection.openDataOutputStream();
    }
    
    /*
     * local device = client
     */
    public Connection(String url) throws IOException {
        m_Url = url;
        m_Connection = (StreamConnection) Connector.open(m_Url);
        m_In = m_Connection.openDataInputStream();
    	m_Out = m_Connection.openDataOutputStream();
    }
    
    public Connection writeString(String s) throws IOException {
    	m_Out.writeUTF(s);
    	autoFlush();
    	return this;
	}

	public String readString() throws IOException {
		return m_In.readUTF();
	}
	
	public int readInt() throws IOException {
		int i = m_In.readInt();
		return i;
	}
	
	public Connection writeInt(int value) throws IOException {
		m_Out.writeInt(value);
    	autoFlush();
    	return this;
	}
	
	public Connection writeByte(byte value) throws IOException {
		m_Out.writeByte(value);
    	autoFlush();
    	return this;
	}
	
	private void autoFlush() throws IOException {
		if (m_AutoFlush) {
			m_Out.flush();
		}
	}
	
	public Connection flush() throws IOException {
		m_Out.flush();
		return this;
	}

	public boolean isAutoFlush() {
		return m_AutoFlush;
	}

	public void setAutoFlush(boolean autoFlush) {
		this.m_AutoFlush = autoFlush;
	}

	public byte readByte() throws IOException {
		return m_In.readByte();
	}
}
